<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Shop;
use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Cache;
use App\Http\Requests\Shop\StoreShopResource;
use App\Http\Requests\Shop\UpdateShopResource;
use App\Http\Requests\Shop\DestroyShopResource;
use App\Http\Requests\Shop\QueryShopCollection;

class ShopController extends Controller
{


	/**
	 * 获取门店数据集合
	 *
	 * Date: 2018/2/1
	 * @author George
	 * @param QueryShopCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(QueryShopCollection $request)
    {
    	$params = $this->validate($request, [
    		'name' => 'nullable',
    		'code' => 'nullable',
    		'address' => 'nullable',
    		'contacts' => 'nullable',
    		'category_id' => 'nullable'
		]);
        // 分页数
        $paginate = $request->get('paginate', 10);
        // 根据门店id查询任务
        $shop_id = $request->shop_id;
        // 是否只返回id
        $is_return_id = $request->get('is_return_id');

		$query = Shop::query();

        foreach ($params as $key => $value) {
        	if ($value) {
        		$query->where($key, 'like', "%".$value."%");
			}
		}
		// 根据门店id查询任务
		if ($shop_id) {
			$query->where('id', $shop_id)->with(['users', 'tasks']);
		}else{
			$query->with(['users:id', 'tasks']);
		}


		// 是否只返回id
		if ($is_return_id) {
			$shop = $query->first();
			return $this->success($shop->tasks()->select(['id'])->pluck('id'));
		}

        $data = $query->orderBy('created_at','desc')->paginate($paginate);


        return $this->success($data);
    }


	/**
	 * 创建门店信息
	 *
	 * Date: 2018/2/5
	 * @author George
	 * @param StoreShopResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function store(StoreShopResource $request)
    {
        $shop = new Shop();

        $attributes = $this->validate($request, [
            'name' => 'required',
            'code' => 'required|unique:shops',
			'category_id' => 'nullable',
			'address' => 'nullable',
			'telephone' => 'nullable',
			'contacts' => 'nullable',
			'mobile' => 'nullable'
        ],[
            'name.required' => '门店名称不能为空',
            'code.required' => '门店编号不能为空',
            'code.unique'   => '门店编号重复',
        ]);


        foreach ($attributes as $key => $value){
            $shop->{$key} = $value;
        }
        $shop->company_id = 1;

        $shop->saveOrFail();

        return $this->stored($shop);
    }

	/**
	 * 根据ID获取门店的信息
	 *
	 * Date: 2018/2/3
	 * @author George
	 * @param Request $request
	 * @param Shop $shop
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Request $request, Shop $shop)
    {
    	//用于获取关联信息
    	$relation = $request->get('relation');
    	//用于判断是否获取ID
    	$onlyid = $request->get('only_id');

    	if ($relation) {
    		$query = $shop->users();
    		if ($onlyid) {
    			return $this->success($query->select('id')->pluck('id'));
			}
			$shop->users = $query->get();
		}

        $shop->tasks;

        // 根据门店id查询任务
        if(count($shop->tasks) > 0){
            foreach ($shop->tasks as $k=>$v){
                if($v['type'] == 'branch'){
                    $shop->tasks[$k]['type'] = 'number';
                }
            }
        }

        return $this->success($shop);

    }


	/**
	 * 更新门店信息
	 *
	 * Date: 2018/2/27
	 * @author George
	 * @param UpdateShopResource $request
	 * @param Shop $shop
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function update(UpdateShopResource $request, Shop $shop)
    {
        // 判断提交门店编号和数据库对应的门店编号是否相等,相等表示没有修改门店编号,就不用验证重复了,
        // 如果不相等,就验证提交的门店编号是否重复,没有重复则可以提交
		$attributes = $this->validate($request, [
			'name' => 'required',
			'code' => [
				'required',
				Rule::unique('shops')->ignore($shop->id)
			],
			'category_id' => 'nullable',
			'address' => 'nullable',
			'telephone' => 'nullable',
			'contacts' => 'nullable',
			'mobile' => 'nullable',
		],[
			'name.required' => '门店名称不能为空',
		]);

        foreach ($attributes as $key => $value){
            $shop->{$key} = $value;
        }
        $shop->saveOrFail();
        // 删除缓存
        Cache::forget("shop:{$shop->id}");
        return $this->updated($shop);
    }


	/**
	 * 删除门店信息
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param DestroyShopResource $request
	 * @param Shop $shop
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
    public function destroy(DestroyShopResource $request, Shop $shop)
    {
        $shop->delete();
        return $this->deleted();
    }

	/**
	 * 同步更新门店关联的人员
	 *
	 * Date: 2018/2/3
	 * @author George
	 * @param UpdateShopResource $request
	 * @param Shop $shop
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function syncMembers(UpdateShopResource $request, Shop $shop)
	{
		$members = $request->get('members');
		if (is_array($members) && count($members) > 0) {
			try {
				$shop->users()->sync($members);
				return $this->success($shop->users()->select(['id'])->pluck('id'));
			} catch (\Exception $exception) {
				return $this->internalError('添加人员到名店失败，请再次尝试');
			}
		}
    }

    /**
     * 同步更新门店关联的任务
     *
     * @author Eric
     * @param UpdateShopResource $request
     * @param Shop $shop
     * @return \Illuminate\Http\JsonResponse
     */
    public function syncTasks(UpdateShopResource $request, Shop $shop)
    {
        $tasks = $request->get('tasks');
        if (is_array($tasks) && count($tasks) > 0) {
            try {
                $shop->tasks()->sync($tasks);
                return $this->success($shop->tasks()->select(['id'])->pluck('id'));
            } catch (\Exception $exception) {
                return $this->internalError('添加人员到名店失败，请再次尝试');
            }
        }
    }

	/**
	 * 门店添加用户
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Shop $shop
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function shop_add_user(Shop $shop, User $user){
        try {
            $shop->users()->attach($user->id);
            return $this->success($shop->users);
        } catch (Exception $e) {
            return $this->failed("添加失败");
        }
    }

	/**
	 * 门店删除用户
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Shop $shop
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function shop_delete_user(Shop $shop, User $user){
        try {
            $shop->users()->detach($user->id);
            return $this->success($shop->users);
        } catch (Exception $e) {
            return $this->failed("删除失败");
        }
    }

	/**
	 * 门店添加任务
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Shop $shop
	 * @param Task $task
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function shop_add_task(Shop $shop, Task $task){
        try {
            $shop->tasks()->attach($task->id);
            return $this->success($shop->tasks);
        } catch (Exception $e) {
            return $this->failed("添加失败");
        }
    }

	/**
	 * 门店删除任务
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Shop $shop
	 * @param Task $task
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function shop_delete_task(Shop $shop, Task $task){
        try {
            $shop->tasks()->detach($task->id);
            return $this->success($shop->tasks);
        } catch (Exception $e) {
            return $this->failed("删除失败");
        }
    }
}
